package com.liwen.kefu.utils;

import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Liwen
 * @createTime: 2024/10/24
 * @description:
 */

@Slf4j
public class JdbcUtil {

    private static Statement statement = null;
    private static Connection conn = null;

    public static Statement getJdbcConn(String host, String port, String userName, String password, String dbName) {
//        String jdbcUrl="jdbc:mysql://10.152.37.9:13316/db_gmcf_ofc?useSSL=false&serverTimezone=GMT%2B8&characterEncoding=utf-8";
        String url = "jdbc:mysql://host:port/dbName?useSSL=false&serverTimezone=GMT%2B8&characterEncoding=utf-8";
        String jdbcUrl = url.replaceAll("host", host).replaceAll("port", port).replaceAll("dbName", dbName);
        String driverName = "com.mysql.jdbc.Driver";
        try {
            Class.forName(driverName);
            conn = DriverManager.getConnection(jdbcUrl, userName, password);
            statement = conn.createStatement();

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return statement;
    }

    public static List<String> executeQuery(String host, String port, String userName, String password, String dbName, String sql, String key) {
        List<String> list = new ArrayList<>();
        if (statement == null) {
            getJdbcConn(host, port, userName, password, dbName);
        }
        try {
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                list.add(resultSet.getString(key));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;

    }


    /**
     * 插入、更新
     *
     * @param host
     * @param port
     * @param dbName
     * @param sql
     */
    public static int executeUpdate(String host, String port, String userName, String password, String dbName, String sql) throws SQLException {
        if (statement == null) {
            getJdbcConn(host, port, userName, password, dbName);
        }
        int count = 0;

        count = statement.executeUpdate(sql);
        if (count > 0) {
            log.info("【mysql 操作成功】===================================");
        }
        return count;
    }

    /**
     * 关流
     */
    public static void close() {
        if (conn != null) {
            try {
                statement.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
